
package io.lckgroup.modules.lck.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.lckgroup.common.utils.R;
import io.lckgroup.modules.lck.dao.MerchantUserDao;
import io.lckgroup.modules.lck.entity.MerchantUserEntity;
import io.lckgroup.modules.lck.form.AppLoginForm;
import io.lckgroup.modules.lck.service.MerchantUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("userService")
public class MerchantUserServiceImpl extends ServiceImpl<MerchantUserDao, MerchantUserEntity> implements MerchantUserService {
    @Autowired
    private MerchantUserDao merchantUserDao;

    @Override
    public MerchantUserEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<MerchantUserEntity>().eq("mobile", mobile));
    }

    @Override
    public R login(AppLoginForm form) {
        MerchantUserEntity user = queryByMobile(form.getMobile());
        if (null == user) {//没有该用户信息
            return R.error("用户不存在").put("user", null);
        } else {
            MerchantUserEntity mue = new MerchantUserEntity();
            Integer isLocked = user.getIsLocked();
            Integer errorCount = user.getLoginErrorCount();
            Date loginErrorTime = user.getLastLoginErrorTime();
            //密码错误时
            if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {

                if (1 == isLocked) {//已经5次失败
                    long nowTime = new Date().getTime();
                    long lastTime = loginErrorTime.getTime();
                    if ((nowTime - lastTime) >= 600 * 1000) {//十分钟后第一次登陆失败
                        mue.setUserId(user.getUserId());
                        mue.setIsLocked(0);
                        mue.setLoginErrorCount(1);
                        mue.setLastLoginErrorTime(null);
                        //TODO 调用SQL更新数据
                        int r = merchantUserDao.updateByDefine(mue);
                        return R.error("登录失败,还有4次机会").put("user", mue);
                    } else {//十分钟内连续登陆
                        //TODO 调用SQL更新数据
                        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                        String format = df.format(new Date(lastTime + 600 * 1000));
                        return R.error("请在" + format + "钟后再试").put("user", null);
                    }
                } else {//未锁定状态
                    if (null == errorCount) {//第一次登陆失败
                        mue.setUserId(user.getUserId());
                        mue.setIsLocked(0);
                        mue.setLoginErrorCount(1);
                        mue.setLastLoginErrorTime(null);
                        //TODO 调用SQL更新数据
                        int r = merchantUserDao.updateByDefine(mue);
                        return R.error("登录失败,还有4次机会").put("user", mue);
                    } else if (errorCount < 4) {
                        mue.setUserId(user.getUserId());
                        mue.setIsLocked(0);
                        mue.setLoginErrorCount(errorCount + 1);
                        mue.setLastLoginErrorTime(null);
                        //TODO 调用SQL更新数据
                        int r = merchantUserDao.updateByDefine(mue);
                        return R.error("登录失败,还有" + (4 - errorCount) + "次机会").put("user", mue);
                    } else {//第5次登陆失败
                        mue.setUserId(user.getUserId());
                        mue.setIsLocked(1);
                        mue.setLoginErrorCount(5);
                        mue.setLastLoginErrorTime(new Date());
                        //TODO 调用SQL更新数据
                        int r = merchantUserDao.updateByDefine(mue);
                        //return R.error("登录失败,还有0次机会").put("user", mue);
                        long nowTime = new Date().getTime();
                        long lastTime = mue.getLastLoginErrorTime().getTime();
                        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                        String format = df.format(new Date(lastTime + 600 * 1000));
                        return R.error("请在" + format + "后再试").put("user", null);
                    }
                }
            } else {
                if (1 == isLocked) {//处理第0次登陆失败
                    long nowTime = new Date().getTime();
                    long lastTime = loginErrorTime.getTime();
                    if ((nowTime - lastTime) < 600 * 1000) {
                        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                        String format = df.format(new Date(lastTime + 600 * 1000));
                        return R.error("请在" + format + "后再试").put("user", null);
                    }
                }
                mue.setUserId(user.getUserId());
                mue.setIsLocked(0);
                mue.setLoginErrorCount(null);
                mue.setLastLoginErrorTime(null);
                //TODO 调用SQL更新数据
                int r = merchantUserDao.updateByDefine(mue);
                return R.ok("登录成功").put("user", mue);
            }
        }
    }

    @Override
    public Map<String, Object> updatePassword(Map<String, Object> params) {
        MerchantUserEntity user = merchantUserDao.selectById(params.get("userId").toString());
        boolean b = user.getPassword()
                .equals(DigestUtils.sha256Hex(params.get("oldpwd").toString()));
        Map<String, Object> r = new HashMap<String, Object>();
        if (b) {//与原始密码相同，可以修改密码
            user.setPassword(DigestUtils.sha256Hex(params.get("confirmpwd").toString()));
            int i = merchantUserDao.updateById(user);
            if (i > 0) {
                r.put("msg", "修改密码成功");
            } else {
                r.put("code", -1);
                r.put("msg", "修改密码失败");
            }
        } else {//原始密码输入有误
            r.put("code", -1);
            r.put("msg", "原密码输入有误");
        }
        return r;
    }

    @Override
    public void resetPassword(Long userId) {
        ArrayList<MerchantUserEntity> commonList = new ArrayList<>();
        MerchantUserEntity userEntity = new MerchantUserEntity();
        userEntity.setUpdateTime(new Date());
        userEntity.setPassword(DigestUtils.sha256Hex("123456"));
        userEntity.setUserId(userId);
        commonList.add(userEntity);
        updateBatchById(commonList);
    }
}
